//
//  AddVisitViewController.m
//  YunGui
//
//  Created by wmm on 16/3/24.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "AddVisitViewController.h"
#import "QBImagePickerController.h"
#import "SubDistrictController.h"
#import "UIWindow+YUBottomPoper.h"
#import "PictureSelectView.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "CameraViewController.h"
#import "ZLAlertView.h"

#define LocationTimeout 3  //   定位超时时间，可修改，最小2s
#define ReGeocodeTimeout 3 //   逆地理请求超时时间，可修改，最小2s

#define TFWIDTH 200.0f
#define TFX 90.0f

@interface AddVisitViewController ()<QBImagePickerControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,SubDistrictControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource,PictureSelectViewDelegate,AMapLocationManagerDelegate>

{
    
    NSArray      *_labelArray;
    UIScrollView * scrollView;
    
    UITableView  *_tableView;
    
    UIScrollView * btnScroll;
    UIScrollView * btn1Scroll;

    
    BOOL isTongQian;
    int typeID;
    NSInteger districtID;
    
    UIView *_placeView;
    UIPickerView *_placePickerView;
    
    NSString *proStr;
    NSString *city;
    NSString *regionStr;
    UIButton *locationBtn;
    
    PictureSelectView *picVew;
    NSMutableArray  *_choosePicDataArray;
    NSMutableArray  *_cameraPicArray;
    NSMutableArray *pic;
    
    NSString *gps;
    NSString *gps_address;
    
    UIView    *_addPickView;
    
    BOOL isSelect;
}
@property (nonatomic, strong)  NSMutableArray *typeDict;
@property (nonatomic, strong) UIPickerView *typePicker;

@property(nonatomic,strong)UISwitch *switchBtn;
@property(nonatomic,strong)UITextField *subDistrictTF;
@property(nonatomic,strong)UITextField *subDistrictTypeTF;
@property(nonatomic,strong)UITextField *nameTF;
@property(nonatomic,strong)UITextField *telTF;
@property(nonatomic,strong)UITextField *locationTF;
@property(nonatomic,strong)UITextField *addressTF;
@property(nonatomic,strong)UITextField *properTF;
@property(nonatomic,strong)UITextField *opponentTF;

@property(nonatomic,strong)UITextView  *visitTV;
@property(nonatomic,strong)UIButton  *addPhotoBtn;
@property(nonatomic,strong)UILabel  *addPhotoLbl;

@property(nonatomic,strong)UIButton  *photoView;

@property (nonatomic, strong) NSMutableArray *allRegionArray;
@property (nonatomic, strong) NSMutableArray *provinceArray;
@property (nonatomic, strong) NSMutableArray *cityArray;
@property (nonatomic, strong) NSMutableArray *regionArray;
@property (nonatomic, strong) NSMutableArray *selectedArray;

@property (nonatomic, strong) AMapLocationManager *locationManager;

@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;

@end

@implementation AddVisitViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = GrayBackColor;
    self.navigationItem.hidesBackButton = YES;
    [ViewTool setNavigationBar:self.navigationController.navigationBar];
    self.navigationItem.title = @"上报拜访";
    self.navigationItem.leftBarButtonItem = [ViewTool getBackBarButtonItemWithTarget:self WithAction:@selector(goToBack)];
    self.navigationItem.rightBarButtonItem = [ViewTool getTitleBarButtonItemWithTarget:self WithTitleString:@"提交" WithAction:@selector(commitVisit:)];

    
    _provinceArray = [NSMutableArray array];
    _cityArray = [NSMutableArray array];
    _regionArray = [NSMutableArray array];
    _selectedArray = [NSMutableArray array];
    _typeDict = [NSMutableArray array];
    isSelect = NO;
    
    [self getRegionData];

    [self initViews];
    [self addPlacePickeView];
    
    gps_address = @"无定位信息";
    gps = [NSString stringWithFormat:@"0,0"];
    [self configLocationManager];
    [self initCompleteBlock];
    
    [self addTypePickeview];
    [self getTypeData];
    
}
- (void)initViews{
    scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64)];
    scrollView.showsVerticalScrollIndicator=NO;
    [self.view addSubview:scrollView];
    
    NSArray *imArr = @[@"Tongqian.png",@"Btn_Normal_Xiaoquming.png",@"Btn_Normal_Liexing2",@"Btn_Nor_Lianxiren",@"Btn_Normal_Dianhua.png",@"Btn_Normal_Diqu.png",@"Btn_Normal_Didian.png",@"Btn_Normal_AiXin.png",@"Btn_Nor_Jingzheng",@"Btn_Normal_Baifangjilu.png"];
    _labelArray=@[@"统签",@"小区名称",@"小区类型",@"联系人",@"联系电话",@"所属地区",@"具体地址",@"物业名称",@"竞争对手",@"拜访记录"];
    
    CGFloat startX = [UIView getWidth:20];
    CGFloat imgW = 20;
    CGFloat labX = startX + imgW +15;
    CGFloat labH = 40;
    CGFloat labY = 10;
    CGFloat height = labH - 2*labY;
    CGFloat grayH = 15;
    CGFloat labW  = 80;
    CGFloat tfX = labX + labW + [UIView getWidth:5];
    CGFloat tfW = kScreenWidth - tfX;
    
    UIView *bgView1 = [self getBgViewWith:CGRectMake(0, 0, kScreenWidth, labH)];
    [scrollView addSubview:bgView1];
    
    UIImageView *labImg = [self imageWith:CGRectMake(startX, labY, imgW, imgW) withName:imArr[0]];
    [bgView1 addSubview:labImg];
    
    UILabel *labLabel = [self getLabelWith:CGRectMake(labX, labY, labW, height) WithTitle:_labelArray[0]];
    [bgView1 addSubview:labLabel];
    
    _switchBtn = [[UISwitch alloc]initWithFrame:CGRectMake(kScreenWidth - 40 - [UIView getWidth:20], labY - 5, 40, 20)];

    _switchBtn.onTintColor=YELLOWCOLOR;    
    [_switchBtn setOn:NO animated:NO];
    [bgView1 addSubview:_switchBtn];
    
    [_switchBtn addTarget:self action:@selector(switchIsChanged:) forControlEvents:UIControlEventValueChanged];
    
    if (_switchBtn.isOn) {
        isTongQian = YES;
    }else{
        isTongQian = NO;
    }
    
    
    UIView *line1 = [self getLineWith:CGRectMake(0, labH - 1, kScreenWidth, 1)];
    [bgView1 addSubview:line1];
    
    //第一区
    UIView *bgView2 = [self getBgViewWith:CGRectMake(0,line1.maxY + grayH, kScreenWidth, labH*4)];
    [scrollView addSubview:bgView2];
    
    UIView *line2 = [self getLineWith:CGRectMake(0, 0, kScreenWidth, 1)];
    [bgView2 addSubview:line2];
    
    for (int i=0; i<4; i++) {
        UIImageView *labImg = [self imageWith:CGRectMake(startX, line2.maxY + labY + i*labH, imgW, imgW) withName:imArr[i+1]];
        [bgView2 addSubview:labImg];
        
        UILabel *labLabel = [self getLabelWith:CGRectMake(labX, line2.maxY + labY + i*labH, labW, height) WithTitle:_labelArray[i+1]];
        [bgView2 addSubview:labLabel];
        
        UIView *line = [self getLineWith:CGRectMake(labX, line2.maxY + labH*(i+1) - 1, kScreenWidth, 1)];
        [bgView2 addSubview:line];
        
        if (i == 3) {
            line.frame = CGRectMake(0, line2.maxY + labH*(i+1)-1, kScreenWidth, 1);
        }
    }
    
    _subDistrictTF = [self addTextFieldWithFrame:CGRectMake(tfX, line2.maxY + labY, tfW, height) AndStr:@"请选择"];
    [bgView2 addSubview:_subDistrictTF];
    
    UIButton *subDistrictBtn = [[UIButton alloc] initWithFrame:CGRectMake(tfX, line2.maxY, tfW, labH)];
    [subDistrictBtn addTarget:self action:@selector(selectSub) forControlEvents:UIControlEventTouchUpInside];
    [bgView2 addSubview:subDistrictBtn];
    
    UIButton *imageBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth -40, line2.maxY + labY , 20, 20)];
    [imageBtn setImage:[UIImage imageNamed:@"Btn_Normal_Xiangyou (1)"] forState:UIControlStateNormal];
    [imageBtn addTarget:self action:@selector(selectSub) forControlEvents:UIControlEventTouchUpInside];
    [bgView2 addSubview:imageBtn];
    
    _subDistrictTypeTF = [self addTextFieldWithFrame:CGRectMake(tfX, _subDistrictTF.maxY + 2*labY, tfW, height) AndStr:@"请选择"];
    [bgView2 addSubview:_subDistrictTypeTF];
    
    UIButton *subDistrictTypeBtn = [[UIButton alloc] initWithFrame:CGRectMake(tfX, _subDistrictTF.maxY + labY, tfW, labH)];
    [subDistrictTypeBtn addTarget:self action:@selector(selectSubType:) forControlEvents:UIControlEventTouchUpInside];
    [bgView2 addSubview:subDistrictTypeBtn];
    
    UIButton *imageTypeBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth -40, _subDistrictTF.maxY + labY*2 , 20, 20)];
    [imageTypeBtn setImage:[UIImage imageNamed:@"Btn_xiangXia"] forState:UIControlStateNormal];
    [imageTypeBtn addTarget:self action:@selector(selectSubType:) forControlEvents:UIControlEventTouchUpInside];
    [bgView2 addSubview:imageTypeBtn];
    
    _nameTF = [self addTextFieldWithFrame:CGRectMake(tfX, _subDistrictTypeTF.maxY + labY, tfW, labH) AndStr:@"必填"];
    [bgView2 addSubview:_nameTF];
    _nameTF.userInteractionEnabled = YES;
    
    _telTF = [self addTextFieldWithFrame:CGRectMake(tfX, _nameTF.maxY, tfW, labH) AndStr:@"必填"];
    _telTF.keyboardType = UIKeyboardTypeNumberPad;
    [bgView2 addSubview:_telTF];
    _telTF.userInteractionEnabled = YES;
    //第二区
    UIView *bgView3 = [self getBgViewWith:CGRectMake(0, bgView2.maxY +grayH, kScreenWidth, labH*4)];
    [scrollView addSubview:bgView3];
    
    UIView *line3 = [self getLineWith:CGRectMake(0, 0, kScreenWidth, 1)];
    [bgView3 addSubview:line3];
    
    for (int i=0; i<4; i++) {
        UIImageView *labImg = [self imageWith:CGRectMake(startX, line3.maxY + labY + i*labH, imgW, imgW) withName:imArr[i+5]];
        [bgView3 addSubview:labImg];
        
        UILabel *labLabel = [self getLabelWith:CGRectMake(labX, line3.maxY + labY + i*labH, labW, height) WithTitle:_labelArray[i+5]];
        [bgView3 addSubview:labLabel];
        
        UIView *line = [self getLineWith:CGRectMake(labX, line3.maxY + labH *(i+1) - 1, kScreenWidth, 1)];
        [bgView3 addSubview:line];
        
        if (i == 3) {
            line.frame = CGRectMake(0, line3.maxY + labH *(i+1)-1, kScreenWidth, 1);
        }
    }
    
    _locationTF = [self addTextFieldWithFrame:CGRectMake(tfX, line3.maxY + labY, tfW - 40, height) AndStr:@"请选择"];
    [bgView3 addSubview:_locationTF];
    _locationTF.userInteractionEnabled = NO;
    
    UIButton *locationBtn1 = [[UIButton alloc] initWithFrame:CGRectMake(tfX, line3.maxY, tfW, labH)];
    [locationBtn1 addTarget:self action:@selector(callplacePicker:) forControlEvents:UIControlEventTouchUpInside];
    [bgView3 addSubview:locationBtn1];
    
    locationBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 40, line3.maxY + (labH - 20)/2, 20, 20)];
    [locationBtn setImage:[UIImage imageNamed:@"Btn_xiangXia"] forState:UIControlStateNormal];
    [locationBtn addTarget:self action:@selector(callplacePicker:) forControlEvents:UIControlEventTouchUpInside];
    [bgView3 addSubview:locationBtn];
    
    
    _addressTF = [self addTextFieldWithFrame:CGRectMake(tfX, _locationTF.maxY + labY, tfW, labH) AndStr:@"请填写"];
    [bgView3 addSubview:_addressTF];
    _addressTF.userInteractionEnabled = YES;
    
    _properTF = [self addTextFieldWithFrame:CGRectMake(tfX, _addressTF.maxY , tfW, labH) AndStr:@""];
    [bgView3 addSubview:_properTF];
    
    _opponentTF = [self addTextFieldWithFrame:CGRectMake(tfX, _properTF.maxY, tfW, labH) AndStr:@""];\
    [bgView3 addSubview:_opponentTF];
    
    //第三区
    UIView *bgView4 = [self getBgViewWith:CGRectMake(0, bgView3.maxY +grayH, kScreenWidth, labH*4 + labW+imgW)];
    [scrollView addSubview:bgView4];
    
    UIView *line4 = [self getLineWith:CGRectMake(0, 0, kScreenWidth, 1)];
    [bgView4 addSubview:line4];
    
    UIImageView *recordImg = [self imageWith:CGRectMake(startX, line4.maxY + labY , imgW, imgW) withName:imArr[9]];
    [bgView4 addSubview:recordImg];
    
    
    UILabel *recordLabel = [self getLabelWith:CGRectMake(labX, line4.maxY + labY , labW, height) WithTitle:_labelArray[9]];
    [bgView4 addSubview:recordLabel];
    
    _visitTV = [[UITextView alloc] initWithFrame:CGRectMake(tfX, recordLabel.y, tfW, labH*3)];
    _visitTV.font = [ViewTool getFont:15.0f];
    _visitTV.textColor = UIColorFromRGB(0x636365);
    _visitTV.layer.borderWidth = 0;
    _visitTV.contentInset = UIEdgeInsetsMake(-8.f, -5.f, -8.f, -5.f);
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 10;// 字体的行间距
    
    NSDictionary *attributes = @{
                                 NSFontAttributeName:_visitTV.font,
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    _visitTV.attributedText = [[NSAttributedString alloc] initWithString:@"" attributes:attributes];
    
    
    [bgView4 addSubview:_visitTV];
    
    picVew = [[PictureSelectView alloc] initWithFrame:CGRectMake(tfX, _visitTV.maxY + labY, _visitTV.width, labW)];
    picVew.isHadCheck = NO;//未检查的时候显示添加按钮
    picVew.delegate =  self;
    picVew.backgroundColor = [UIColor whiteColor];
    [bgView4 addSubview:picVew];
    
    bgView4.height = picVew.maxY+10;
    
    UIView *line = [self getLineWith:CGRectMake(0, bgView4.height -1, kScreenWidth, 1)];
    [bgView4 addSubview:line];
    
    UILabel *exampleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, bgView4.maxY+labY, kScreenWidth - 22, 12)];
    exampleLabel.text = @"* 只支持jpg、png、gif格式图片，文件大小最大10MB";
    exampleLabel.textColor = GRAYCOLOR;
    exampleLabel.textAlignment = NSTextAlignmentRight;
    exampleLabel.font = [ViewTool getFont:13.0f];
    [scrollView addSubview:exampleLabel];
    
    scrollView.contentSize = CGSizeMake(kScreenWidth, exampleLabel.maxY + 5);
    
}
#pragma mark --添加 类型选择的pickerview
- (void)addTypePickeview
{
    _addPickView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    _addPickView.hidden = YES;
    [self.view addSubview:_addPickView];
    
    CGFloat pickerH = 260.0f;
    
    UIView * bgBlackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth,kScreenHeight - pickerH)];
    bgBlackView.backgroundColor = [UIColor blackColor];
    bgBlackView.alpha = 0.6;
    [_addPickView addSubview:bgBlackView];
    
    
    UIView *pView = [[UIView alloc] initWithFrame:CGRectMake(0, bgBlackView.maxY, kScreenWidth, pickerH)];
    pView.backgroundColor = [UIColor whiteColor];
    [_addPickView addSubview:pView];
    
    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(0, 0 , kScreenWidth, 1) withBackgroudColor:GRAYLINECOLOR];
    [pView addSubview:line1];
    
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, line1.maxY + 5, 50, 30)];
    [leftBtn setTitle:@"取消" forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(hanldeSelected:) forControlEvents:UIControlEventTouchUpInside];
    [leftBtn setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
    leftBtn.titleLabel.font = [ViewTool getFont:15.0f];
    [pView addSubview:leftBtn];
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(pView.width - 10 - 50, line1.maxY + 5, 50, 30)];
    [rightBtn setTitle:@"确定" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [ViewTool getFont:15.0f];
    [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(hanldeSelected:) forControlEvents:UIControlEventTouchUpInside];
    [pView addSubview:rightBtn];
    
    UIView *line = [ViewTool getLineViewWith:CGRectMake(0, rightBtn.maxY + 5 , kScreenWidth, 1) withBackgroudColor:GRAYLINECOLOR];
    [pView addSubview:line];
    
    _typePicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, line.maxY  , kScreenWidth, pView.height - 30 -70)];
    [pView addSubview:_typePicker];
    _typePicker.delegate = self;
    _typePicker.dataSource = self;
    
}
- (void)selectSubType:(UIButton *)btn{
    
    if (btn.selected == NO) {
        [UIView animateWithDuration:0.25 animations:^{
            _addPickView.hidden = NO;
        }];
        
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            _addPickView.hidden = YES;
        }];
    }
    [_typePicker reloadAllComponents];
    
}
- (void)hanldeSelected:(UIButton *)btn{
    _addPickView.hidden = YES;
    if ([btn.currentTitle isEqualToString:@"确定"]) {
        NSInteger row = [_typePicker selectedRowInComponent:0];
        _subDistrictTypeTF.text = _typeDict[row][@"title"];
        
        typeID = [_typeDict[row][@"id"] intValue];
    }else{
        
        }

}
#pragma mark --获取小区类型
- (void)getTypeData
{
    int isCache;
    NSString *currentTime = [DateTool getCurrentDate];
    NSString *timeString = [[NSUserDefaults standardUserDefaults] objectForKey:@"getTypeTime"];
    if (timeString != nil) {
        NSInteger diffTime = [DateTool getTimesDiffTimeFrom:timeString To:currentTime];
        if (diffTime > 24) {
            isCache = 1;
        }else{
            isCache = 0;
        }
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:currentTime forKey:@"getTypeTime"];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"method" : @"app.village.type",@"isCache" : @(isCache)}];
    
    NSDictionary *parames = [DataTool addSignToDic:dict];
    [DataTool postWithUrl:HEAD_URL parameters:parames success:^(id data) {
        id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
        _typeDict = backData[@"data"][@"allType"];
        
        [_typePicker reloadAllComponents];
    } fail:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}

- (void)switchIsChanged:(UISwitch *)swit{
    if (isTongQian) {
        isTongQian = NO;
    }else{
        isTongQian = YES;
    }
}

-(void)uploadImages{
    if (picVew.allPicArray.count == 1) {
        [self uploadImage:picVew.allPicArray[0] success:^(id data) {
            [self addVisit];
        } fail:^(NSError *error) {
            
        }];
    }else if (picVew.allPicArray.count == 2){
        [self uploadImage:picVew.allPicArray[0] success:^(id data) {
            [self uploadImage:picVew.allPicArray[1] success:^(id data1) {
                [self addVisit];
            } fail:^(NSError *error) {
                
            }];
        } fail:^(NSError *error) {
            
        }];
    }else if (picVew.allPicArray.count == 3){
        [self uploadImage:picVew.allPicArray[0] success:^(id data) {
            [self uploadImage:picVew.allPicArray[1] success:^(id data1) {
                [self uploadImage:picVew.allPicArray[2] success:^(id data2) {
                    [self addVisit];
                } fail:^(NSError *error) {
                    
                }];
            } fail:^(NSError *error) {
                
            }];
        } fail:^(NSError *error) {
            
        }];
    }
}

#pragma mark - Action Handle

- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    [self.locationManager setAllowsBackgroundLocationUpdates:NO];
    
    [self.locationManager setLocationTimeout:LocationTimeout];
    
    [self.locationManager setReGeocodeTimeout:ReGeocodeTimeout];
    
}

- (void)cleanUpAction
{
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
}

- (void)reGeocodeAction
{
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];
}

#pragma mark - Initialization

- (void)initCompleteBlock
{
    __weak AddVisitViewController *wSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error){
        NSLog(@"initCompleteBlock");
        if (location){
            NSLog(@"%@",[NSString stringWithFormat:@"%@ \n %@-%@-%.2fm", regeocode.formattedAddress,regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]);
            NSLog(@"%@",[NSString stringWithFormat:@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy]);
            
            if (regeocode.formattedAddress != nil && regeocode.formattedAddress.length > 0) {
                gps_address = regeocode.formattedAddress;
            }
            gps = [NSString stringWithFormat:@"%f,%f",location.coordinate.longitude,location.coordinate.latitude];            
        }
//            if (error){
//            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
//            [SVProgressHUD dismiss];
//            wSelf.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:wSelf action:@selector(commitVisit:)];
//            NSLog(@"error:%@",error);
//            [Tools showMessage:@"定位失败" view:wSelf];
//        }
        [wSelf uploadImages];
        [wSelf cleanUpAction];
    };
}

- (void)uploadImage:(NSData *)imgData success:(SuccessBlock)successBlock fail:(FailBlock)faileBlock{
    [DataTool uploadPic:imgData success:^(id data) {
        NSLog(@"%@",data);
        NSString *status = [(NSDictionary *)data objectForKey:@"status"];
        if ([status isEqualToString:@"SUCCESS"]) {
            NSString *picUrl = [[(NSDictionary *)data objectForKey:@"data"] objectForKey:@"pic"];
            [pic addObject:picUrl];
            successBlock(data);
        }else{
            NSString *msg = [(NSDictionary *)data objectForKey:@"msg"];
            [SVProgressHUD dismiss];
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(commitVisit:)];
            [Tools showMessage:msg view:self];
        }
    } fail:^(NSError *error) {
        [SVProgressHUD dismiss];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(commitVisit:)];
        [Tools showMessage:@"图片上传失败" view:self];
    }];
}

#pragma mark - 提交
- (void)addVisit{

    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    [dictionary setObject:@"app.visit.store" forKey:@"method"];

    NSNumber *tq;
    if (isTongQian) {
        tq = [NSNumber numberWithInt:2];
    }else{
        tq = [NSNumber numberWithInt:1];
    }
    
    [dictionary setObject:_model.DistrictID forKey:@"village_id"];
    [dictionary setObject:tq forKey:@"is_merge"];
    [dictionary setObject:@(districtID) forKey:@"district_id"];//区县id
    [dictionary setObject:@(typeID) forKey:@"type_id"];
    [dictionary setObject:_addressTF.text forKey:@"address"];

    [dictionary setObject:gps forKey:@"gps"];
    [dictionary setObject:gps_address forKey:@"gps_address"];
    [dictionary setObject:_visitTV.text forKey:@"desc"];
    [dictionary setObject:_nameTF.text forKey:@"contact"];
    [dictionary setObject:_telTF.text forKey:@"tel"];
    NSString *picStr = [NSString stringWithFormat:@"%@",[pic componentsJoinedByString:@","]];
    
    [dictionary setObject:picStr forKey:@"image"];
    
    [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dictionary] success:^(id data) {
        [SVProgressHUD dismiss];
        self.navigationItem.rightBarButtonItem = [ViewTool getTitleBarButtonItemWithTarget:self WithTitleString:@"提交" WithAction:@selector(commitVisit:)];
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString *status = [(NSDictionary *)jsonDic objectForKey:@"status"];
        NSLog(@"返回 %@",jsonDic);
        if ([status isEqualToString:@"SUCCESS"]) {
            [_delegate passValue:@"SUCCESS"];
            isSelect = NO;
            [self goToBack11];
        }else{
            NSString *code = [(NSDictionary *)jsonDic objectForKey:@"code"];
            NSString *msg = [(NSDictionary *)jsonDic objectForKey:@"msg"];
            NSLog(@"%@%@%@",status,code,msg);
            [Tools showMessage:msg view:self];
        }
    } fail:^(NSError *error) {
        [SVProgressHUD dismiss];
        self.navigationItem.rightBarButtonItem = [ViewTool getTitleBarButtonItemWithTarget:self WithTitleString:@"提交" WithAction:@selector(commitVisit:)];
        NSLog(@"error:%@",error);
        [Tools showMessage:@"新建失败" view:self];
    }];
}

#pragma mark --定位的方法
- (void)localization
{
    if ([CLLocationManager locationServicesEnabled] &&
        ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized
         || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
            [SVProgressHUD show];
            self.navigationItem.rightBarButtonItem=nil;
            //定位功能可用，开始定位
            [self initCompleteBlock];
            [self configLocationManager];
            [self reGeocodeAction];
        }
    else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
        [Tools showMessage:@"提示:您未开启定位，请先开启定位。" view:self];
    }
}

- (void)commitVisit:(id)sender{
    
    pic = [NSMutableArray array];
    if (_subDistrictTF.text == nil | [_subDistrictTF.text length] == 0 ){
        [self.view makeToast:@"请选择小区"];
        return;
    }
    if (_subDistrictTypeTF.text == nil | [_subDistrictTypeTF.text length] == 0 ){
        [self.view makeToast:@"请选择小区类型"];
        return;
    }
    if (_nameTF.text == nil | [_nameTF.text length] == 0 ){
        [self.view makeToast:@"请填写联系人"];
        return;
    }
    if (_telTF.text == nil | [_telTF.text length] == 0 ){
        [self.view makeToast:@"请填写联系电话"];
        return;
    }
    if (![JudgeNumber boolenPhone:_telTF.text]){
        [self.view makeToast:@"请填写正确的联系电话"];
        return;
    }
    if (_locationTF.text == nil | [_locationTF.text length] == 0 ){
        [self.view makeToast:@"请选择地区"];
        return;
    }
    if (_addressTF.text == nil | [_addressTF.text length] == 0 ){
        [self.view makeToast:@"请填写地址"];
        return;
    }
    if (_visitTV.text == nil | [_visitTV.text length] == 0 ){
        [self.view makeToast:@"请填写拜访记录"];
        return;
    }
    if (picVew.allPicArray.count == 0){
        [self.view makeToast:@"请上传照片"];
        return;
    }
    if (districtID  == 0){
        [self.view makeToast:@"小区区县数据为空无法新建,请重新选择地区"];
        return;
    }
    if (typeID == 0){
        [self.view makeToast:@"小区类型数据为空无法新建,请重新选择小区"];
        return;
    }
    if ([_visitTV.text length] < 30 ){
        [self.view makeToast:@"拜访记录不少于30个字"];
        return;
    }
    
    [self localization];
}

#pragma mark --SubDistrictControllerDelegate小区
- (void)chooseDistrict:(SubDistrictDetailModel *)model{
    _model = model;
    
    _subDistrictTF.text = _model.title;
    _locationTF.text = [NSString stringWithFormat:@"%@ %@ %@",_model.province,_model.city,_model.district];
    districtID = [_model.district_id integerValue];
    _addressTF.text = _model.address;
    _properTF.text = _model.property;
    _opponentTF.text = _model.competitor;
    isSelect = YES;
    
}

- (void)selectSub{
    NSLog(@"selectSub");
    SubDistrictController *subDistrictController = [[SubDistrictController alloc] init];
    subDistrictController.isChooseDistrict = YES;
    subDistrictController.isTongQian = isTongQian;
    
    subDistrictController.delgate = self;
    [self.navigationController pushViewController:subDistrictController animated:YES];
}


#pragma mark --添加 地区选择的pickerview
- (void)addPlacePickeView{
    
    _placeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    _placeView.hidden = YES;
    [self.view addSubview:_placeView];
    
    CGFloat pickerH = 260;
    
    UIView * bgBlackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth,kScreenHeight - pickerH)];
    bgBlackView.backgroundColor = [UIColor blackColor];
    bgBlackView.alpha = 0.6;
    [_placeView addSubview:bgBlackView];
    
    UIView *pView = [[UIView alloc] initWithFrame:CGRectMake(0, bgBlackView.maxY, kScreenWidth,pickerH)];
    pView.backgroundColor = [UIColor whiteColor];
    [_placeView addSubview:pView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapToHideBlackView:)];
    [bgBlackView addGestureRecognizer:tapGesture];
    
    
    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(0, 0 , kScreenWidth, 1) withBackgroudColor:GRAYLINECOLOR];
    [pView addSubview:line1];
    
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, line1.maxY + 5, 50, 30)];
    [leftBtn setTitle:@"取消" forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(hanldePlaceSelected:) forControlEvents:UIControlEventTouchUpInside];
    [leftBtn setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
    leftBtn.titleLabel.font = [ViewTool getFont:15.0f];
    [pView addSubview:leftBtn];
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(_placeView.width - 10 - 50, line1.maxY + 5, 50, 30)];
    [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [ViewTool getFont:15.0f];
    [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(hanldePlaceSelected:) forControlEvents:UIControlEventTouchUpInside];
    [pView addSubview:rightBtn];
    
    UIView *line = [ViewTool getLineViewWith:CGRectMake(0, rightBtn.maxY + 5 , kScreenWidth, 1) withBackgroudColor:GRAYLINECOLOR];
    [pView addSubview:line];
    
    
    _placePickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, line.maxY , kScreenWidth, pView.height - 30-70)];
    [pView addSubview:_placePickerView];
    _placePickerView.delegate = self;
    _placePickerView.dataSource = self;
    
}

- (void)getRegionData
{
    
    int isCache;
    NSString *currentTime = [DateTool getCurrentDate];
    NSString *timeString = [[NSUserDefaults standardUserDefaults] objectForKey:@"getRegionTime"];
    if (timeString != nil) {
        NSInteger diffTime = [DateTool getTimesDiffTimeFrom:timeString To:currentTime];
        if (diffTime > 24) {
            isCache = 1;
        }else{
            isCache = 0;
        }
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:currentTime forKey:@"getRegionTime"];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"method" : @"app.region.all",@"isCache":@(isCache)}];
    NSDictionary *parames = [DataTool addSignToDic:dict];
    [DataTool postWithUrl:HEAD_URL parameters:parames success:^(id data) {
        id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
        _allRegionArray = backData[@"data"][@"allRegion"];
        
        for (int i = 0; i<_allRegionArray.count; i++) {
            NSDictionary *provinceDict = _allRegionArray[i];
            if (provinceDict) {
                [_provinceArray addObject:provinceDict];
            }
            
            self.selectedArray = _provinceArray.firstObject[@"city"];
            if (self.selectedArray.count > 0) {
                self.cityArray = _provinceArray.firstObject[@"city"];
            }
            if(self.cityArray.count> 0){
                self.regionArray = self.cityArray.firstObject[@"district"];
            }
        }
        [_placePickerView reloadAllComponents];
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}


- (void)callplacePicker:(UIButton *)btn
{
    if (btn.selected == NO) {
        [UIView animateWithDuration:0.25 animations:^{
            
            _placeView.hidden = NO;
            
        }];
        if (self.provinceArray.count != 0) {
            proStr =  [self.provinceArray objectAtIndex:[_placePickerView selectedRowInComponent:0]][@"region"];
        }
        if (self.cityArray.count != 0) {
            city = [self.cityArray objectAtIndex:[_placePickerView selectedRowInComponent:1]][@"region"];
        }
        if (self.regionArray.count != 0) {
            regionStr = [self.regionArray objectAtIndex:[_placePickerView selectedRowInComponent:2]][@"region"];
        }
        
    }else{
        [UIView animateWithDuration:0.25 animations:^{
            _placeView.hidden = YES;
            
        }];
    }
    btn.selected = !btn.selected;
    [_placePickerView reloadAllComponents];
}
- (void)hanldePlaceSelected:(UIButton *)btn
{
    locationBtn.selected = NO;
    _placeView.hidden = YES;
    
    if ([btn.currentTitle isEqualToString:@"完成"]) {
    
        [_locationTF setText:[NSString stringWithFormat:@"%@ %@ %@",proStr,city,regionStr]];
        
        districtID = [[self.regionArray objectAtIndex:[_placePickerView selectedRowInComponent:2]][@"id"]  integerValue];
     }else{
        
    }
    
}
- (void)tapToHideBlackView:(UITapGestureRecognizer *)tap{
    
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if(pickerView ==_typePicker){
        return 1;
    }else if (pickerView == _placePickerView){
        return 3;
    }
    return 0;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if(pickerView == _placePickerView){
        if (component ==0) {
            return _provinceArray.count;
        }else if(component == 1){
            return _cityArray.count;
        }else{
            return _regionArray.count;
        }
        
    }else if (pickerView == _typePicker){
        return _typeDict.count;
    }
    return 0;
    
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView == _typePicker) {
        return _typeDict[row][@"title"];
    }else{
        if (component == 0) {
            return _provinceArray[row][@"region"];
        }else if (component == 1) {
            return _cityArray[row][@"region"];
        }else{
            return _regionArray[row][@"region"];
        }
    }

    return @"";
    
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if(pickerView == _typePicker){
        
    }else{
    if (component == 0) {
        _selectedArray = self.provinceArray[row][@"city"];
        if (_selectedArray.count > 0) {
            self.cityArray = _selectedArray;
        }else{
            self.cityArray = nil;
        }
        if (self.cityArray.count > 0) {
            self.regionArray = _cityArray.firstObject[@"district"];
        } else {
            self.regionArray = nil;
        }
    }
    [pickerView selectedRowInComponent:1];
    [pickerView reloadComponent:1];
    [pickerView selectedRowInComponent:2];
    if (component == 1) {
        if (self.selectedArray.count > 0 && self.cityArray.count > 0) {
            self.regionArray = [self.selectedArray objectAtIndex:row][@"district"];
        } else {
            self.regionArray = nil;
        }
        [pickerView selectRow:1 inComponent:2 animated:YES];
    }
    [pickerView reloadComponent:2];
        
    if (self.provinceArray.count > 0) {
        proStr = [self.provinceArray objectAtIndex:[pickerView selectedRowInComponent:0]][@"region"];
    }
    if (self.cityArray.count > 0) {
        city = [self.cityArray objectAtIndex:[pickerView selectedRowInComponent:1]][@"region"];
    }
    if (self.regionArray.count > 0) {
        regionStr = [self.regionArray objectAtIndex:[pickerView selectedRowInComponent:2]][@"region"];
    }
    
    [_locationTF setText:[NSString stringWithFormat:@"%@ %@ %@",proStr,city,regionStr]];
    }
}

#pragma mark --点击添加照片
- (void)addImage
{
    if(picVew.allPicArray.count == 3){
        [Tools showMessage:@"最多选择3张照片哦" view:self];
    }else{
    if(IsIOS8Lower){
        UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"打开手机相册",@"手机相机拍摄", nil];
        [actionSheet showInView:self.view];
    }else{
        UIAlertController * alertionControll = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction * action1 = [UIAlertAction actionWithTitle:@"打开手机相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self takePictureInPhone1];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"手机相机拍摄" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self takePictureWithCamera];
        }];
        UIAlertAction * action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alertionControll addAction:action1];
        [alertionControll addAction:action2];
        [alertionControll addAction:action3];
        if(alertionControll != nil){
            [self presentViewController:alertionControll animated:YES completion:nil];
        }
    }
    }
}

#pragma mark --actionSheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self takePictureInPhone1];
    }else if (buttonIndex == 1){
        [self takePictureWithCamera];
    }
}
- (void)actionSheetCancel:(UIActionSheet *)actionSheet
{
    [actionSheet dismissWithClickedButtonIndex:2 animated:YES];
}

- (void)takePictureInPhone1
{
    if(![Tools isAllowPhoto]){
        [Tools showMessage:@"APP无相册访问权限，请先设置!" view:self];
        return;
    }
    
    if (![QBImagePickerController isAccessible]) {
        [Tools showMessage:@"相机不可用哦" view:self];
    }
    QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.maximumNumberOfSelection = 3;//最大上传5张
    
    if (picVew.allPicArray.count >= 3) {
        [Tools showMessage:@"最多选择3张照片哦" view:self];
        return;
    }else if (picVew.allPicArray.count == 2){
        imagePickerController.maximumNumberOfSelection = 1;
    }else if (picVew.allPicArray.count == 1){
        imagePickerController.maximumNumberOfSelection = 2;
    }else if (picVew.allPicArray.count == 0){
        imagePickerController.maximumNumberOfSelection = 3;//最大上传5张
    }
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
    [self presentViewController:navigationController animated:YES completion:NULL];
}
#pragma mark -- QBImage代理
- (void)imagePickerController:(QBImagePickerController *)imagePickerController didSelectAssets:(NSArray *)assets
{
    _choosePicDataArray = [NSMutableArray array];

    if (assets.count > 3) {
        [Tools showMessage:@"最多选择3张照片哦" view:imagePickerController];
        return;
    }
    
    [self dismissImagePickerController];
    for(int i = 0 ;i< assets.count; i ++){
        ALAssetRepresentation *resentation = [assets[i]  defaultRepresentation];
        UIImage *image = [UIImage imageWithCGImage:[resentation fullResolutionImage]];
        
        NSData *data = UIImageJPEGRepresentation(image, 0.3);
        
        [_choosePicDataArray addObject:data];
    }
    picVew.images = _choosePicDataArray;

    if (picVew.allPicArray.count >= 3) {
        picVew.isHideBtn = YES;
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)dismissImagePickerController
{
    if (self.presentedViewController) {
        [self dismissViewControllerAnimated:YES completion:NULL];
    }
}

- (void)imagePickerControllerDidCancel1:(QBImagePickerController *)imagePickerController
{
    [self dismissImagePickerController];
}

- (void)takePictureWithCamera
{
    if(![Tools isAllowTakePhoto]){
        [Tools showMessage:@"APP无相机访问权限，请先设置!" view:self];
        return;
    }
    
    CameraViewController *cameraVC = [[CameraViewController alloc] init];
    cameraVC.isShouldBack = YES;//这个是要拍完照 返回
    cameraVC.isHaveRuleBtn = YES;
    [self presentViewController:cameraVC animated:YES completion:nil];
    cameraVC.backBlock = ^(NSData *data,NSData *data1){
        _cameraPicArray = [NSMutableArray array];
        if(picVew.allPicArray.count >= 2){
            picVew.isHideBtn = YES;
        }
        if (picVew.allPicArray.count < 4) {
            [_cameraPicArray addObject:data];
        }else{
            [Tools showMessage:@"最多选择3张哦" view:self];
        }
        picVew.images = _cameraPicArray;
    };
}

-(UIView *)getBgViewWith:(CGRect)frame
{
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}
- (UIImageView *)imageWith:(CGRect)frame withName:(NSString *)str{
    UIImageView *img = [[UIImageView alloc]initWithFrame:frame];
    img.image = [UIImage imageNamed:str];
    return img;
}
- (UILabel *)getLabelWith:(CGRect)frame WithTitle:(NSString *)title
{
    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = title;
    label.textColor = GRAYCOLOR;
    label.textAlignment = NSTextAlignmentLeft;
    label.font = [ViewTool getFont:16.0f];
    return label;
}

-(UIView *)getLineWith:(CGRect)frame
{
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = UIColorFromRGB(0xe8e7ec);
    return view;
}
-(UITextField *)addTextFieldWithFrame:(CGRect)frame AndStr:(NSString *)placeholder
{
    UITextField *textF=[[UITextField alloc]initWithFrame:frame];
    textF.userInteractionEnabled = NO;
    textF.textColor = UIColorFromRGB(0x646368);
    textF.placeholder=placeholder;
    [textF setValue:PLACECOLOR forKeyPath:@"_placeholderLabel.textColor"];
    textF.font = [ViewTool getFont:16.0f];
    [textF setValue:[ViewTool getFont:16.0f] forKeyPath:@"_placeholderLabel.font"];
    return textF;
}
- (void)goToBack11{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)goToBack{
    
    if (_nameTF.text.length > 0 | _telTF.text.length > 0 | _visitTV.text.length > 0){
        isSelect = YES;
    }
    
    if (isSelect) {
        ZLAlertView *alert = [[ZLAlertView alloc]initWithTitle:@"提示" message:@"拜访未提交是否需要返回"];
        [alert addBtnTitle:@"取消" action:^{
            
        }];
        [alert addBtnTitle:@"确定" action:^{
            [self cleanUpAction];
            self.completionBlock = nil;
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [alert showAlertWithSender:self];
    }else{
        [self cleanUpAction];
        self.completionBlock = nil;
        [self.navigationController popViewControllerAnimated:YES];
    }

}

@end